<template>
  <div class="setwrap">
    <div class="titlecommon">
      基础设备管理
    </div>
    <div class="panelben">
      <div class="titlecommon2">
        <span>
          基础设施
        </span>
        <div class="btn" @click="goMap"> 
          <el-icon><MapLocation /></el-icon>
          <span class="text">
            农场地图
          </span>
        </div>
      </div>
      <div class="tab">
        <div @click="changeTab(index)" :class="[activeIndex==index?'tabchildActive':'','tabchild']" v-for="(item,index) in menu" :key="index">
          {{ item }}
        </div>
      </div>
      <div class="flexcenter22"> 
        <div class="flexcenter2" v-if="(userRole == 'admin-farmer')">
          <div class="btn btn2" @click="openAdd" v-if='addType'>
                <el-icon><Plus /></el-icon>
                <span class="text">
                  新增
                </span>
          </div>
          
          <div class="btn btn2 btn3 "  @click="openAddMore">
              <el-icon><Plus /></el-icon>
              <span class="text">
                批量新增
              </span>
          </div>
           <div class="btn btn2 btn3" @click="editRoad" v-if="activeIndex<2&&multiId" >
              <el-icon><Edit /></el-icon>
              <span class="text">
                编辑{{activeIndex==0?'路网':'水网'}}
              </span>
          </div>
          <div class="btn btn2 btn3 btn34" @click="deleteRoad" v-if="activeIndex<2&&multiId" >
              <el-icon><Delete /></el-icon>
              <span class="text">
                删除{{activeIndex==0?'路网':'水网'}}
              </span>
          </div>
         
        </div>
        <div class="chooseWater" v-if='activeIndex<2'>
          <div class="name1">{{activeIndex==0?'路网':'水网'}}名称:</div>
          <el-select @change='waterChange'  v-model="chooseWater" class="m-2" placeholder="请选择" size="default">
                    <el-option
                    v-for="item in waterList.value"
                    :key="item.id"
                    :label="item.infrastructureName"
                    :value="item.id"
                    />
          </el-select>
        </div>
      </div>
      
      
      <div class="table">
        <el-table v-if='activeIndex<2' :data="tableData2.value" style="width: 100%">
          <el-table-column prop="inodeName" label="点位">
            
            <template #default="scope">
              {{ scope.row.inodeName+'('+scope.row.infrastructureName+')' }}
            </template>
          </el-table-column>
          <el-table-column prop="lon" label="经度" />
          <el-table-column prop="lat" label="纬度" />
          <el-table-column prop="handle" label="操作" v-if="(userRole == 'admin-farmer')">
            <template #default="scope">
              <div class="btnwrap">
                <div class="btntext" @click="editOne2(scope.row)">编辑</div>
                <div class="btntext delete" @click="delOne2(scope.row)">删除</div>    
              </div>  
            
            </template>
          </el-table-column>
         
        </el-table>
        <el-table v-else :data="tableData.value" style="width: 100%">
          <el-table-column prop="infrastructureName" label="名称" />
          <el-table-column prop="nickName" label="种植户" />
          <el-table-column prop="plotName" label="地块" />
          <el-table-column prop="address" label="位置" />
          <el-table-column prop="lon" label="经度" />
          <el-table-column prop="lat" label="纬度" />
          <el-table-column prop="buildTime" label="添加时间" />
          <el-table-column prop="handle" label="操作" v-if="(userRole == 'admin-farmer')">
            <template #default="scope">
              <div class="btnwrap">
                <div class="btntext" @click="editOne(scope.row)">编辑</div>
                <div class="btntext delete" @click="delOne(scope.row)">删除</div>    
              </div>  
            
            </template>
          </el-table-column>
         
        </el-table>
        <div class="fy">
        <div class="total flexcenter">
          共 <span>{{ pageInfo.total }}</span
          >项数据
        </div>
        <el-pagination
          :currentPage="pageInfo.pageNum"
          @current-change="currentChange"
          background
          layout="prev, pager, next"
          :total="pageInfo.total"
        />
      </div>
      </div>
      
    </div>
    <add-more @refreshList='getListAndOption' :type='type' ref="addmore"/>
    <add-set @getList='getList' :plotList="plotOptionList.value"  ref="addSetRef" />
    <el-dialog
            v-model="dialogVisiblePoint"
            title="编辑点位"
            width="570px"
            custom-class="diyclass"
        >
            <div class="mcontent">
            <div class="mchild">
                <div class="label">
                经度:
                </div>
                <el-input 
                type="number" 
                v-model="formP.value.lon"
                placeholder="请输入"  ></el-input>
                
            </div> 
            <div class="mchild">
                <div class="label">
                纬度:
                </div>
                <el-input 
                type="number"  
                v-model="formP.value.lat"
                placeholder="请输入"></el-input>
                
            </div> 
            </div>
            <template #footer>
            <span class="dialog-footer">
                <el-button :disabled="overFlag" @click="submit">提交</el-button>
                <el-button type="primary" @click="dialogVisiblePoint=false">
                取消
                </el-button>
            </span>
            </template>
        </el-dialog>
        <el-dialog
            v-model="editRoadFlag"
            :title="activeIndex==0?'路网重命名':'水网重命名'"
            width="570px"
            custom-class="diyclass"
        >
            <div class="mcontent">
            <div class="mchild">
                <div class="label">
                {{activeIndex==0?'路网':'水网'}}名称:
                </div>
                <el-input  
                v-model="rename"
                placeholder="请输入"  ></el-input>
                
            </div> 
            </div>
            <template #footer>
            <span class="dialog-footer">
                <el-button :disabled="overFlag" @click="editRoadsure">提交</el-button>
                <el-button type="primary" @click="editRoadFlag=false">
                取消
                </el-button>
            </span>
            </template>
        </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, onUnmounted } from "vue";
import { useRouter } from 'vue-router'
import { post, get,deletePost } from "@/public/request/api";
import { ElMessage } from "element-plus";
import { ElMessageBox } from "element-plus";
import addMore from '../plantingType/modal/addMore.vue'
import bus from '@/utils/bus'
import addSet from '../plantingType/modal/addDevice.vue'
import storage from "@/store";
export default defineComponent({
  components: {
    addMore,
    addSet
  },
  setup() {
    //变量
    const userRole = storage.state.userRole;
    let rename=ref('')
    let activeIndex=ref(0)
    let editRoadFlag=ref(false)
    let dialogVisiblePoint=ref(false)
    const menu=[
      '路网',
      '水网',
      '泵房/井房',
      '水池',
      '仓库',
      '入水口',
      '出水口',
      '阀控器',
      
    ]
    let waterList=reactive({
      value:[
        
      ]
    })
    let pageInfo = reactive({
      pageSize: 10,
      pageNum: 1,
      total: 0,
    });
    
    let chooseWater=ref(null)
    let addType=ref(false)
    let type=ref('')
    let plotOptionList = reactive({
      value: [],
    });
    let formP=reactive({
      value:{
        id:null,
        lat:null,
        lon:null
      }
    })
    let form=reactive({
      value:{
        pageNum:1,
        pageSize:10,
        infrastructureName:'',
      }
    })
    const router = useRouter()
    let dialogVisible=ref(false)
    let tableData=reactive({
      value:[]
    })
    let tableData2=reactive({
      value:[]
    })
    let multiId=ref('')
    
    function getPlotOptionList() {
      get("/plot/options", {
        isExclude: 1,
      }).then((res) => {
        plotOptionList.value = res.data;
      });
    }
   function goMap(){
    bus.emit('menuChange', 0);
    router.push({ path: '/farmlandData/statistics' })
   }
   function waterChange(e) {
     console.log(e);
     if(e==0){
       multiId.value=''
     }else{
       multiId.value=e
     }
     getList()
   }
   function getRoadOption(type,id=null){
      get("/multiInfrastructure/options", {
         infrastructureType: type,
      }).then((res) => {
        if(!id){
          multiId.value=''
          chooseWater.value=null
        }else{
          multiId.value=id
          chooseWater.value=id
        }
        
        waterList.value=[]
        
        if(res.data.length>0){
          res.data.unshift({
            infrastructureName:'全部',
            id:0
          })
        }
        waterList.value=res.data
        
      });
   }
   function submit() {
     post("/multiInfrastructure/edit", formP.value).then((res) => {
        ElMessage({
            message: "编辑成功",
            type: "success",
        });
        getList()
      })
   }
   function changeTab(index){
    activeIndex.value=index
    chooseWater.value=null
    multiId.value=''
    if(index<2){
      addType.value=false
      getRoadOption(index)
    }else{
      addType.value=true
      
    }
    getList()
   }
   
   function currentChange(e) {
      pageInfo.pageNum = e;
      getList();
    }
   function getList(){
    if(activeIndex.value<2){
      
      get("/multiInfrastructure/page", {
        pageNum:pageInfo.pageNum,
        pageSize:pageInfo.pageSize,
        infrastructureType:activeIndex.value,
        multiId:multiId.value
      }).then((res) => {
        tableData2.value=res.pageInfo.list
        pageInfo.total=res.pageInfo.total
      })
    }else{
      get("/simpleInfrastructure/page", {
        pageNum:pageInfo.pageNum,
        pageSize:pageInfo.pageSize,
        infrastructureType:activeIndex.value,
        
      }).then((res) => {
        tableData.value=res.pageInfo.list
        pageInfo.total=res.pageInfo.total
      })
    }
    
   }
   function openAddMore(){
     if(activeIndex.value==0){
       type.value='deviceroad'
     }else if(activeIndex.value==1){
       type.value='devicewater'
     }else{
       type.value='device'
     }
    
    this.$refs.addmore.dialogVisible=true
   }
   function openAdd(){
      this.$refs.addSetRef.dialogVisible=true
      this.$refs.addSetRef.name=menu[activeIndex.value]
      this.$refs.addSetRef.form.value.infrastructureType=activeIndex
       this.$refs.addSetRef.init(false)
    }
    function editOne(val){
     this.$refs.addSetRef.dialogVisible=true
      this.$refs.addSetRef.name=menu[activeIndex.value]
      this.$refs.addSetRef.form.value.infrastructureType=activeIndex
      this.$refs.addSetRef.init(val)
   }
   function editOne2(val){
     formP.value.id=val.id
     formP.value.lat=val.lat
     formP.value.lon=val.lon
     dialogVisiblePoint.value=true
    }
    function deleteRoad() {
     ElMessageBox.confirm("确认删除?")
        .then(() => {
          deleteRoadSure()
        })
        .catch(() => {
          // catch error
        });
    }
    function editRoad() {
      console.log(waterList);
      console.log(multiId.value);
      
      let find=waterList.value.find(item=>{
        return item.id==multiId.value
      })
      console.log('find',find);
      rename.value=find.infrastructureName
      editRoadFlag.value=true
    }
    function editRoadsure(){

      post("/multiInfrastructure/rename", {
              id:multiId.value,
              "infrastructureName":rename.value
            }).then((res) => {
              ElMessage({
                  message: "编辑成功",
                  type: "success",
              });
              editRoadFlag.value=false
              getRoadOption(activeIndex.value,multiId.value)
            });
    }
    function deleteRoadSure(){

      deletePost("/multiInfrastructure/delAll", {
              id:multiId.value
            }).then((res) => {
              ElMessage({
                  message: "删除成功",
                  type: "success",
              });
              multiId.value=''
              getList()
              getRoadOption(activeIndex.value)
            });
    }
    function delOne(id) {
      ElMessageBox.confirm("确认删除?")
        .then(() => {
          delHandel(id.id);
        })
        .catch(() => {
          // catch error
        });
    }
    function delHandel(id) {
      deletePost("/simpleInfrastructure/del", {
        id
      }).then((res) => {
        ElMessage({
            message: "删除成功",
            type: "success",
        });
        getList()
      });
    }
    function delOne2(id) {
      ElMessageBox.confirm("确认删除?")
        .then(() => {
          delHandel2(id.id);
        })
        .catch(() => {
          // catch error
        });
    }
    function delHandel2(id) {
      deletePost("/multiInfrastructure/del", {
        id
      }).then((res) => {
        ElMessage({
            message: "删除成功",
            type: "success",
        });
        getList()
      });
    }
    function getListAndOption() {
      getList()
      if(activeIndex.value<2){
        getRoadOption(activeIndex.value)
      }
      
    }
    function reInit() {
      getList()
      getPlotOptionList()
      getRoadOption(activeIndex.value)
    }
    
    // 生命周期
    onMounted(() => {
      getList()
      getPlotOptionList()
      getRoadOption(0)
      bus.on('changeBase',reInit);
    });

    onUnmounted(() => {
      bus.off('changeBase', reInit);
    });

    //methods

    // return
    return {
      editRoadFlag,
      getListAndOption,
      deleteRoad,
      multiId,
      waterChange,
      dialogVisiblePoint,
      editOne,
      editOne2,
      currentChange,
      pageInfo,
      tableData2,
      waterList,
      chooseWater,
      plotOptionList,
      addType,
      type,
      openAdd,
      changeTab,
      form,
      submit,
      formP,
      userRole,
      menu,
      activeIndex,
      dialogVisible,
      tableData,
      goMap,
      openAddMore,
      delOne,
      editRoad,
      delOne2,
      getList,
      rename,
      editRoadsure
    };
  },
});
</script>

<style lang="scss">
.setwrap{
  .el-table th.el-table__cell,.el-table .el-table__cell,.el-table tr,.el-table--fit{
    background: transparent!important;
    color: #fff!important;
  }
  .el-table th.el-table__cell.is-leaf,.el-table td.el-table__cell{
    border-bottom: 1px solid rgba(255, 255, 255, 0.08)!important
  }
  .el-pagination.is-background .el-pager li{
    background: transparent!important;
    color: #fff!important;
  }
  .el-pagination.is-background .btn-next{
    background: none!important;
  }
  .btn-prev{
    background: none!important;
  }
}
</style>
<style lang="scss" scoped>
@import "@/assets/scss/index.scss";
.btn34{
  background: rgb(245, 98, 98) !important;
}
.chooseWater{
  font-size: 14px;
  display: flex;
  align-items: center;
  margin-top: 20px;
  .name1{
    margin-right: 5px;
  }
  }
.flexcenter22{
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.flexcenter2{
  display: flex;
  align-items: center;
}

.setwrap{
  .btn3{
    width: 100px!important;
    margin-left: 10px;
  }
  .fy{
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .total{
      color: rgba(255, 255, 255, 0.60);
      font-size: 10px;
      span{
        font-size: 20px;
      }
    }
    
  }
  .table{
    margin-top: 20px;
  }
  .btnwrap{
    display: flex;
    align-items: center;
    .btntext{
      color:rgba(49, 127, 245, 1) ;
      cursor: pointer;
    }
    .delete{
      color: rgba(245, 98, 98, 1)!important;
      margin-left: 15px;
    }
  }
  .titlecommon2{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .btn2{
    width: 72px;
    box-sizing: border-box;
    padding: 5px 10px!important;
    margin-top: 20px;
  }
  .btn{
    display: flex;
    align-items: center;
    justify-content: space-between;
    line-height: 20px;
      background: rgba(9, 127, 229, 1);
      font-size: 14px;
      padding: 5px 20px;
      border-radius: 5px;
      cursor: pointer;
      .text{
        margin-left: 10px;
        position: relative;
        top: 2px;
      }
  }
  .tab{
    display: flex;
    align-items: center;
    margin-top: 20px;
    
    .tabchildActive{
      color: rgba(49, 154, 245, 1)!important;
      background: rgba(49, 154, 245, .16)!important;
    }
    .tabchild{
      cursor: pointer;
      padding: 4px 13px;
      border-radius: 100px;
      color: rgba(255, 255, 255, 0.60);
      background: rgba(255, 255, 255, 0.08);
      margin-right: 20px;

    }
  }
}

</style>
